package pl.enigmatic.parser.xml;

@SuppressWarnings("rawtypes")
public class BasicFinalPropertyParser<G extends BasicFinalPropertyParser.Getter> extends BasicPropertyParser<G> implements ObjectCreator {

	protected static abstract class Getter extends pl.enigmatic.parser.xml.BasicPropertyParser.Accessor {

		protected Getter(String propertyName, Class<?> type) {
			super(propertyName, type, Parser.createParser(type));
		}

		@Override
		public boolean access(final Object target, final Object value, final ParsingInfo<?> info) {
			return true;
		}

		public abstract Object get(final String property, final Object target);
	}

	protected BasicFinalPropertyParser(final Parser<?> owner) {
		super(owner, false);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object createInstance(final ParsingInfo info) {
		final Parser parser = info.getParentParser();
		if (parser == owner) {
			final NodeNameInfo name = info.getNodeInfo();
			if (name != null) {
				final String property = name.getProperty();
				final Object target = info.getParent().getTarget();
				if (target != null && accessors.containsKey(property)) { return accessors.get(property).get(property, target); }
			}
		} else if (parser != null) {
			final ObjectCreator other = parser.getCreator(getClass());
			if (other != null) { return other.createInstance(info); }
		}
		return null;
	}
}
